// "use strict";
import fs from "fs";
import os from "os"
import { writeFile, readFile } from 'node:fs/promises';
import path from "path";
import process from "process";
import { safeAwait } from "./commonUtil";
import pkg from '/package.json'

export function getPath() {
    let storePath;
    // let appname = process.env.npm_package_name;
    let appname = pkg.name;
    if (os.platform == "win32") {
        // console.info('get path', process, pkg, pkg.name);
        let abosulteDir = path.resolve(process.env.APPDATA, appname);
        storePath = path.resolve(abosulteDir, "store.json");
    } else {
        storePath = path.resolve(os.homedir(), ".config", appname, "store.json");
    }
    return storePath;
}


export async function storeSet(key, value, options = {
    force: false
}) {
    //判断key是否为字符串
    if (typeof (key) != "string") {
        throw new Error(`set: ${key} is not a string`);
    }

    let storePath = getPath();
    let content, readerror;
    //判断文件是否存在,如不存在则创建文件并写入{}
    if (!fs.existsSync(storePath)) {
        content = "{}";
    } else {
        //读文件内容
        [content, readerror] = await safeAwait(readFile(storePath, {
            encoding: "utf8"
        }));
        if (readerror) {
            console.error(`readFile: ${storePath} error: ${readerror}`);
            throw new Error(`readFile: ${storePath} error: ${readerror}`);
        }
        //如果内容为空则content = "{}"
        if (content == "") {
            content = "{}";
        }
    }
    console.debug("storeSet Content", content)
    let obj = {};

    //对读取的内容进行序列化
    try {
        obj = JSON.parse(content);
    } catch (error) {
        if (options.force) {
            obj = {};
        }
        else {
            console.error(`parse: ${content} error: ${error}`);
            throw new Error(`parse: ${content} error: ${error}`);
        }
    }

    obj[key] = value;

    console.debug("storeSet writeFile Content", obj)
    //JSON对象反序列化并写入到文件中
    const [ret, error] = await safeAwait(writeFile(storePath, JSON.stringify(obj)));
    if (error) {
        console.error(`writeFile: ${storePath}, error: ${error}`);
        throw new Error(`writeFile: ${storePath}, error: ${error}`);
    }
};

export async function storeGet(key, defaultVal) {

    if (typeof (key) != "string") {
        throw new Error(`get: ${key} is not a string`);
    }
    let storePath = getPath();
    if (!fs.existsSync(storePath)) {
        return null;
    }
    let obj = {};

    let [content, readerror] = await safeAwait(readFile(storePath, {
        encoding: "utf8"
    }));
    if (readerror) {
        console.error(`readFile: ${storePath} error: ${readerror}`);
        throw new Error(`readFile: ${storePath} error: ${readerror}`);
    }
    if (content == "") {
        return null;
    }
    try {
        obj = JSON.parse(content);
    } catch (error) {
        console.error(`parse: ${content} error: ${error}`);
        throw new Error(`parse: ${content} error: ${error}`);
    }

    return obj[key] ? obj[key] : defaultVal;
};

export function storeGetSync(key, defaultVal) {

    if (typeof (key) != "string") {
        throw new Error(`get: ${key} is not a string`);
    }
    let storePath = getPath();
    if (!fs.existsSync(storePath)) {
        return defaultVal;
    }
    let obj = {};

    let content = fs.readFileSync(storePath, {
        encoding: "utf8"
    });
    if (content == "") {
        return defaultVal;
    }
    try {
        obj = JSON.parse(content);
    } catch (error) {
        console.error(`parse: ${content} error: ${error}`);
        throw new Error(`parse: ${content} error: ${error}`);
    }

    return obj[key] ? obj[key] : defaultVal;
};

export async function storeRemove(key) {
    if (typeof (key) != "string") {
        throw new Error(`remove: ${key} is not a string`);
    }
    let storePath = getPath();
    if (!fs.existsSync(storePath)) {
        return;
    }
    let obj = {};
    let [content, readerror] = await safeAwait(readFile(storePath, {
        encoding: "utf8"
    }));
    if (readerror) {
        console.error(`readFile: ${storePath} error: ${readerror}`);
        throw new Error(`readFile: ${storePath} error: ${readerror}`);
    }
    if (content == "") {
        return;
    }
    try {
        obj = JSON.parse(content);
    } catch (error) {
        console.error(`parse: ${content} error: ${error}`);
        throw new Error(`parse: ${content} error: ${error}`);
    }

    try {
        Reflect.deleteProperty(obj, key);
    } catch (error) {
        console.error(`remove: ${obj, key}, error: ${error}`);
        throw new Error(`remove: ${obj, key}, error: ${error}`);
    }

    const [ret, error] = await safeAwait(writeFile(storePath, obj));
    if (error) {
        console.error(`parse: ${content} error: ${error}`);
        throw new Error(`parse: ${content} error: ${error}`);
    }
};

//清空文件内容
export async function clearStore() {
    let storePath = getPath();
    if (!fs.existsSync(path)) {
        return;
    }
    //创建文件并写入{}
    const [writeret, error] = await safeAwait(writeFile(storePath, {}));
    if (error) {
        console.error(`writeFile: ${storePath} error: ${error}`);
        throw new Error(`writeFile: ${storePath} error: ${error}`);
    }
}
